<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\prepay\gateway;

use addons\epay\library\Service;
use app\common\library\InviteCode;
use app\common\manager\BaseManager;
use app\common\manager\GroupManager;
use app\common\manager\OrderManager;
use app\common\manager\PayLogManager;
use app\common\manager\UserAccountManager;
use app\common\model\assistant\Assistant;
use app\common\model\AssistantOrder;
use app\common\model\Config;
use app\common\model\Coupon;
use app\common\model\Order;
use app\common\model\SignUp;
use app\common\model\Team;
use app\common\model\UserAccount;
use app\common\model\UserCoupon;
use app\common\model\UserTeam;
use think\Db;
use think\Exception;

class Group
{
    CONST METHOD = 'Group';

    CONST TYPE_ALIPAY = 1;
    CONST TYPE_WECHAT = 2;
    public function order($user, $request,$isTrans=true)
    {
        $is_success = 0;
        if ($isTrans)
            Db::startTrans();
        try {
            $prePayment = null;
            $type = $request['type'] ?? 'wechat';
            $orderId = $request['orderId'] ?? '';
            $method = $request['method'] ?? 'JSAPI';
            $relationId = $request['relationId'] ?? 0;
            $is_balance = $request['isBalance'] ?? 0;
            $userCouponId = $request['userCouponId'] ?? 0;
            //$assistantIds = $request['assistantIds'] ?? '';
            $signId = $request['signId'] ?? 0;
            $assistantArr  = $assistantMoneyArr = [];
            $assistantCount = 0;
            if (!$user->is_authentication){
                throw new Exception('您未实名认证，无法操作');
            }

            if (!$relationInfo = Team::where('t_id',$relationId)->find()) {
                throw new Exception('关联订单信息不存在');
            }
            $assistantIds = '';
            $orderInfo = Order::where('po_id',$orderId)->where('type',Order::TYPE_TEAM)->where('expire_time','>',time())->find();
            $assistantIdsArr = $assistantList = $assistantDistanceArr = [];
            if (!$orderInfo) {
                $assistantIds = $relationInfo['assistant_ids'] ?? '';
            }else{
                $assistantIds = $orderInfo['assistant_ids'] ?? '';
            }
            if ($relationInfo['captain']!= $user->id){
                $assistantIds = '';
            }
            if ($relationInfo['captain']!= $user->id && $assistantIds){
                throw new Exception('您不是队长，无法选择助教');
            }else{
                if($assistantIds){
                    if(!$relationInfo['lat'] || !$relationInfo['long'] || !$relationInfo['address']){
                        throw new Exception('组队地址信息有误，无法选择助教');
                    }
                    $lat = $relationInfo['lat'];
                    $lng = $relationInfo['long'];
                    $address = $relationInfo['address'];
                    $assistantIdsArr = explode(',', $assistantIds);
                    if (count($assistantIdsArr) > ($relationInfo['number_people']-1)){
                        throw new Exception('助教数量不能大于组队人数');
                    }
                    $h = intval(date('H',time()));
                    $i = date('i',time());
                    $compare = $h.$i;
                    $assistantModel = new Assistant();
                    $assistantList = $assistantModel->alias('a')
                        ->join('assistant_time t','t.assistant_id = a.id','inner')
                        ->where('a.id','in',$assistantIdsArr)
                        ->where('a.user_id','<>',$user->id)
                        ->where('t.compare_start','<=',$compare)
                        ->where('t.compare_end','>=',$compare)
                        ->where('a.status',Assistant::STATUS_ENABLE)
                        ->where('a.review_status',Assistant::REVIEW_STATUS_PASS)
                        ->where('a.order_switch',Assistant::ORDER_SWITCH_ON)
                        ->where('a.in_service',Assistant::IN_SERVICE_STATUS_OFF)
                        ->field('a.id,a.user_id,a.nickname,a.lat,a.lng,a.address,a.avatar,a.gender,a.birthday,a.order_switch,a.in_service,a.level,a.introduce,a.type,a.store_id,a.assistant_price,a.time_unit')
                        ->group('a.id')
                        ->select();
                    if (count($assistantList)!= count($assistantIdsArr)) {
                        throw new Exception('助教信息有误，请重新选择');
                    }
                    $assistantMoney = $assistantDistanceAmount =0;
                    $totalTime = bcsub($relationInfo['end_date'],$relationInfo['start_date']);
                    $totalMinute = bcdiv($totalTime,60,2);
                    foreach ($assistantList as $assistant) {

                        if ($assistant->user_id == $user->id) {
                            throw new Exception('助教不能是自己');
                        }
                        $totalNumber = ceil(bcdiv($totalMinute,$assistant['time_unit'],2));
                        $assistantMoneyArr[$assistant['id']] = bcmul($totalNumber,$assistant['assistant_price'],2);
                        $assistantMoney = bcadd(bcmul($totalNumber,$assistant['assistant_price'],2),$assistantMoney,2);
                        $assistantArr[$assistant['id']] = $assistant;

                        $exceedAmount = 0.00;
                        $baseMileage = Config::where('name','basic_mileage')->value('value');
                        $baseMileagePrice = Config::where('name','basic_mileage_price')->value('value');
                        $exceed_price = Config::where('name','exceed_price')->value('value');

                        $distance = haversine($lat,$lng,$assistant['lat'],$assistant['lng']);
                        $exceed_distance = ceil(bcsub($distance,$baseMileage,2));

                        if($exceed_distance){
                            $exceedAmount = bcmul($exceed_distance,$exceed_price,2);
                        }
                        $exceedAmount = max($exceedAmount, 0.00);
                        $assistantTravelAmount = bcadd($baseMileagePrice,$exceedAmount ,2);
                        $assistantDistanceArr[$assistant['id']] = [
                            'distance' => $distance,
                            'base_mileage' => $baseMileage,
                            'base_mileage_price' => $baseMileagePrice,
                            'exceed_price' => $exceed_price,
                            'exceed_distance' => $exceed_distance,
                            'distance_amount' => $assistantTravelAmount,
                            'lat'=>$lat,
                            'lng'=>$lng,
                            'address'=>$address,
                            'exceed_amount'=>$exceedAmount,
                        ];
                        $assistantDistanceAmount = bcadd($assistantDistanceAmount,$assistantTravelAmount,2);
                        $info = \app\common\model\assistant\Order::where('assistant_id',$assistant['id'])
                            ->where('status','<>',\app\common\model\assistant\Order::STATUS_END)
                            ->where('pay_status',\app\common\model\assistant\Order::PAY_STATUS_YES)
                            ->select();
                        if ($info){
                            foreach ($info as $order) {
                                if ($order['status'] == \app\common\model\assistant\Order::STATUS_REFUND && $order['pay_status'] == \app\common\model\assistant\Order::PAY_STATUS_REFUND){
                                    continue;
                                }
                                if ($order['order_start_time'] <= $relationInfo['start_date'] && $order['order_end_time'] >= $relationInfo['start_date']){
                                    throw new Exception($assistant['nickname'].'助教已有订单，无法参与');
                                }else if($order['order_start_time'] <= $relationInfo['end_date'] && $order['order_end_time'] >= $relationInfo['end_date']){
                                    throw new Exception($assistant['nickname'].'助教已有订单，无法参与');
                                }
                            }
                        }
                    }
                }


            }

            $userCouponInfo = null;
            if (!$orderInfo) {
                if ($userCouponId) {
                    $userCouponInfo = UserCoupon::where('id', $userCouponId)->where('user_id', $user->id)->find();
                    if (!$userCouponInfo) {
                        throw new Exception('优惠券信息有误，无法使用');
                    }

                    if ($userCouponInfo['expires_time'] < time()) {
                        throw new Exception('优惠券已过期，无法使用');
                    }

                    if (!$assistantIds){
                        if ($userCouponInfo['detail'] != Coupon::DETAIL_TEAM) {
                            throw new Exception('优惠券类型有误，无法使用');
                        }
                    }else{
                        if ($userCouponInfo['detail'] != Coupon::DETAIL_TEAM && $userCouponInfo['detail'] != Coupon::DETAIL_PLAYER) {
                            throw new Exception('优惠券类型有误，无法使用');
                        }
                    }

                    if ($userCouponInfo['block'] == UserCoupon::BLOCK_YES) {
                        throw new Exception('优惠券已被使用，无法使用');
                    }

                }
            }else{
                $userCouponId = $orderInfo['user_coupon_id'] ?? 0;
                $userCouponInfo = UserCoupon::where('id', $userCouponId)->where('user_id', $user->id)->find();
            }

            if ($user->level < $relationInfo['level']){
                throw new Exception('您当前会员等级不可参与');
            }

            if ($relationInfo['number_people'] <=  $relationInfo['join_number']){
                throw new Exception('当前组队已满员，无法参与');
            }

            if ($relationInfo['start_date'] < time()) {
                throw new Exception('当前组队已开始，无法参与');
            }

//            if ($relationInfo['cost'] < 0.01){
//                throw new Exception('订单金额有误，无法创建订单');
//            }


            if(!$signId){
                throw new Exception('请选择名片');
            }else if (!SignUp::where('id',$signId)->where('user_id',$user->id)->find()) {
                throw new Exception('当前名片信息有误，请正确操作');
            }
            $time_expire = config('app.time_expire') ?? 5;
            $time_expire = bcadd(time(), bcmul($time_expire,60));
            if ($type == 'wechat'){
                $time_expire = date('YmdHis', $time_expire);
            }else if ($type == 'alipay'){
                $time_expire = date('Y-m-d H:i:s', $time_expire);
            }

            /**
             * 如果已下单 ，将无法再下单
             * 如果有已下单未支付的订单，将重新拉起未支付订单
             *
             */
            if (Order::where('user_id',$user->id)->where('type',Order::TYPE_TEAM)->where('relation_id',$relationId)->where('pay_state',Order::PAY_STATE_SUCCESS)->count()) {
                throw new Exception('已下单，无法重复下单');
            }

            /**
             * 如果传参orderId ,在上面条件通过的情况下，将拉起传参过来的订单
             */
            $assistantCount = 0;
            $result = [];
            $pref_amount = 0.00;
            if ( !empty($orderInfo)) {
                $basicOrder = Order::where('user_id',$user->id)->where('is_basic',Order::IS_BASIC_YES)->where('type',Order::TYPE_TEAM)->where('relation_id',$relationId)->where('order',$orderInfo['order'])->find();

                $real_money = bcadd($orderInfo['real_money'],0,2);
                if ($basicOrder){
                    $real_money = bcadd($orderInfo['real_money'],$real_money,2);
                }
                $order = $orderInfo['order'];
                $orderData = ['id'=>$orderId,'time_expire'=>$orderInfo['expire_time']];
                $result['code'] = BaseManager::$successCode;
                $result['message'] = BaseManager::$successMessage;
                $result['data'] = $orderData;
                if (!empty($orderInfo['assistant_ids'])){
                    $assistantCount = count(explode(',',$orderInfo['assistant_ids']));
                }else{
                    $assistantCount = 0;
                }
                $prePayment = json_decode($orderInfo['pre_payment'],true);
            }else{
                $assistantCount = count($assistantIdsArr);
                if ($relationInfo['type'] == Team::TYPE_CONTRACT){
                    if ($user->id == $relationInfo['captain']){

                        $teamMoney = $money = $real_money = bcmul(bcadd($relationInfo['cost'],0,2),$relationInfo['number_people'],2);
                        if ($assistantCount > 0){
                            $money = bcadd($money,$assistantMoney,2);
                            $money = bcadd($money,$assistantDistanceAmount,2);
                            $real_money = $money;
                        }

                        if($userCouponInfo){
                            if ($userCouponInfo['detail'] == Coupon::DETAIL_TEAM) {
                                if ($userCouponInfo['limit_amount'] > $teamMoney){
                                    throw new Exception('当前金额未满足优惠券使用条件，无法使用');
                                }
                                if($userCouponInfo['type'] == Coupon::TYPE_FULL){
                                    $real_money = bcsub($money,$userCouponInfo['amount'],2);
                                    $pref_amount = $userCouponInfo['amount'];
                                }else if ($userCouponInfo['type'] == Coupon::TYPE_DISCOUNT && $userCouponInfo['rate'] > 0){
                                    $real_money = bcsub($money,bcdiv(bcmul($teamMoney,$userCouponInfo['rate'],2),100,2),2);
                                    $pref_amount = bcsub($money,$real_money,2);
                                }


                            }else if ($userCouponInfo['detail'] == Coupon::DETAIL_PLAYER) {
                                if ($userCouponInfo['limit_amount'] > $assistantMoney) {
                                    throw new Exception('当前金额未满足优惠券使用条件，无法使用');
                                }

                                if ($userCouponInfo['type'] == Coupon::TYPE_FULL) {
                                    $real_money = bcsub($money, $userCouponInfo['amount'],2);
                                    $pref_amount = $userCouponInfo['amount'];
                                } else if ($userCouponInfo['type'] == Coupon::TYPE_DISCOUNT && $userCouponInfo['rate'] > 0) {
                                    $real_money = bcsub($money,bcdiv(bcmul($assistantMoney, $userCouponInfo['rate'], 2), 100, 2),2);
                                    $pref_amount = bcsub($money, $real_money, 2);
                                }

                            }

                            if (!UserCoupon::where('id', $userCouponInfo['id'])->update(['block' => UserCoupon::BLOCK_YES,'update_time'=>time()])){
                                throw new Exception('优惠券使用失败，请稍后再试');
                            }

                        }
                    }else{
                        $money = $real_money = 0.00;
                    }
                }else{
                    $costCount = $assistantCount ? $assistantCount + 1 : 1;
                    $teamMoney = $money = $real_money = bcmul(bcadd($relationInfo['cost'],0,2), $costCount,2);
                    if ($assistantCount > 0){
                        $money = bcadd($money,$assistantMoney,2);
                        $money = bcadd($money,$assistantDistanceAmount,2);
                        $real_money = $money;
                    }
                    if($userCouponInfo){
                        if ($userCouponInfo['detail'] == Coupon::DETAIL_TEAM) {
                            if ($userCouponInfo['limit_amount'] > $teamMoney) {
                                throw new Exception('当前金额未满足优惠券使用条件，无法使用');
                            }

                            if ($userCouponInfo['type'] == Coupon::TYPE_FULL) {
                                $real_money = bcsub($money, $userCouponInfo['amount'], 2);
                                $pref_amount = $userCouponInfo['amount'];
                            } else if ($userCouponInfo['type'] == Coupon::TYPE_DISCOUNT && $userCouponInfo['rate'] > 0) {
                                $real_money = bcsub($money,bcdiv(bcmul($teamMoney, $userCouponInfo['rate'], 2), 100, 2));
                                $pref_amount = bcsub($money, $real_money, 2);
                            }
                        }else if ($userCouponInfo['detail'] == Coupon::DETAIL_PLAYER) {
                            if ($userCouponInfo['limit_amount'] > $assistantMoney) {
                                throw new Exception('当前金额未满足优惠券使用条件，无法使用');
                            }

                            if ($userCouponInfo['type'] == Coupon::TYPE_FULL) {
                                $real_money = bcsub($money,$userCouponInfo['amount'], 2);
                                $pref_amount = $userCouponInfo['amount'];
                            } else if ($userCouponInfo['type'] == Coupon::TYPE_DISCOUNT && $userCouponInfo['rate'] > 0) {
                                $real_money = bcsub($money,bcdiv(bcmul($assistantMoney, $userCouponInfo['rate'], 2), 100, 2),2);
                                $pref_amount = bcsub($money, $real_money, 2);
                            }

                        }
                        if (!UserCoupon::where('id', $userCouponInfo['id'])->update(['block' => UserCoupon::BLOCK_YES, 'update_time' => time()])) {
                            throw new Exception('优惠券使用失败，请稍后再试');
                        }
                    }
                }



                $order = orderNum();
                $data['order'] = $order;
                $data['user_id'] = $user->id;
                $data['order_money'] = $money;
                $data['real_money'] = $real_money;
                $data['user_coupon_id'] = $userCouponInfo['id']??0;
                $data['pref_money'] = $pref_amount;
                $data['relation_id'] = $relationInfo['t_id'];
                $data['assistant_ids'] = $assistantIds;
                $data['is_balance'] = $is_balance;
                $data['expire_time'] = strtotime($time_expire);
                $data['extend_param'] = serialize(array_merge(['signId'=>$signId],$assistantDistanceArr));
                $data['ct_date'] = time();
                if (!Team::where(['t_id'=>$relationInfo['t_id'],'ordered_number'=>Db::raw('ordered_number < number_people')])->update(['ordered_number'=>Db::raw('ordered_number + '.($assistantCount + 1)),'up_date'=>time()])) {
                    throw new Exception('当前人数预下单数量已满，无法下单');
                }


                $result = OrderManager::Order($user,$data,\app\common\model\Order::TYPE_TEAM,false);
                $result['data']['time_expire'] = strtotime($time_expire);
                if ($result['code']!=OrderManager::$successCode){
                    throw new Exception($result['message']);
                }

                if ($user->id == $relationInfo['captain']){
                    $basicOrder['order'] = $order;
                    $basicOrder['user_id'] = $user->id;
                    $basicOrder['order_money'] = $money;
                    $basicOrder['real_money'] = $relationInfo['basic_price'];
                    $basicOrder['user_coupon_id'] = 0;
                    $basicOrder['pref_money'] = 0.00;
                    $basicOrder['relation_id'] = $relationInfo['t_id'];
                    $basicOrder['is_balance'] = $is_balance;
                    $basicOrder['is_basic'] = Order::IS_BASIC_YES;
                    $basicOrder['expire_time'] = strtotime($time_expire);
                    $basicOrder['extend_param'] = serialize(array_merge(['signId'=>$signId],$assistantDistanceArr));
                    $basicOrder['ct_date'] = time();
                    $resultBasic = OrderManager::Order($user,$basicOrder,\app\common\model\Order::TYPE_TEAM,false);
                    if ($resultBasic['code']!=OrderManager::$successCode){
                        throw new Exception($resultBasic['message']);
                    }
                    $real_money = bcadd($real_money,$relationInfo['basic_price'],2);
                }


                if ($assistantArr){
                    $assistantOrder = $userAssistantOrder = [];
                    $average = $totalAverage = 0;
                    if ($userCouponInfo){
                        $average = bcdiv($pref_amount,$assistantCount,2);
                    }
                    $totalAssistant = count($assistantList);
                    foreach ($assistantList as $assistantKey => $assistant){
                        $totalAverage = bcadd($totalAverage,$average,2);
                        $assistantOrder[$assistantKey] = [
                            'assistant_id' => $assistant['id'],
                            'user_id' => $assistant['user_id'],
                            'order' => $order,
                            'orderer' => $user->id,
                            'order_id' => $result['data']['id'],
                            'amount' => $assistantMoneyArr[$assistant['id']],
                            'distance_amount' => $assistantDistanceArr[$assistant['id']]['distance_amount'],
                            'discount_amount' => $assistantKey == ($totalAssistant-1) ? bcsub($pref_amount,$totalAverage,2) : $average,
                            'real_amount' => $assistantKey == ($totalAssistant-1) ? bcsub(bcadd($assistantMoneyArr[$assistant['id']],$assistantDistanceArr[$assistant['id']]['distance_amount'],2),bcsub($pref_amount,$totalAverage,2),2) : bcsub(bcadd($assistantMoneyArr[$assistant['id']],$assistantDistanceArr[$assistant['id']]['distance_amount'],2),$average,2),
                            'order_start_time' => $relationInfo['start_date'],
                            'order_end_time' => $relationInfo['end_date'],
                            'extends'=>serialize($assistantDistanceArr[$assistant['id']]),
                            'create_time' => time(),
                            'update_time' => time(),
                        ];

                        $userAssistantOrder[$assistantKey] = [
                            'assistant_id' => $assistant['id'],
                            'user_id' => $user->id,
                            'order' => $order,
                            'order_id' => $result['data']['id'],
                            'amount' => $assistantMoney,
                            'discount_amount' => $pref_amount,
                            'real_amount' => $real_money,
                            'distance_amount' => $assistantTravelAmount,
                            'order_start_time' => $relationInfo['start_date'],
                            'order_end_time' => $relationInfo['end_date'],
                            'extends'=>serialize($assistantDistanceArr[$assistant['id']]),
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }

                    if ($assistantOrder){
                        if(!\app\common\model\assistant\Order::insertAll($assistantOrder)){
                            throw new Exception('助教订单创建失败');
                        }
                    }

                    if ($userAssistantOrder){
                        if(!AssistantOrder::insertAll($userAssistantOrder)){
                            throw new Exception('用户助教订单创建失败');
                        }
                    }
                }
            }



            if($relationInfo['type'] == Team::TYPE_CONTRACT && $user->id != $relationInfo['captain']){
                $is_balance = 1;
            }
            if ($is_balance && $result['code']==OrderManager::$successCode){
                $userAccount = UserAccount::where('user_id',$user->id)->find();
                if (!$userAccount){
                    throw new Exception('当前用户账户信息有误，无法使用此功能');
                }

                if ($userCouponInfo){
                    if (!UserCoupon::where('id', $userCouponInfo['id'])->update(['block' => UserCoupon::BLOCK_NO, 'status' => UserCoupon::STATUS_USED, 'update_time' => time()])) {
                        throw new Exception('优惠券使用失败，请稍后再试');
                    }
                }

                file_put_contents('money.txt','order:'.$order.',real_money:'.$real_money,FILE_APPEND);
                $result2 = UserAccountManager::money($user->id,$real_money,UserAccountManager::CHANGE_TYPE_PAYMENT,time(),UserAccountManager::TYPE_TEAM,['relation_id'=>$result['data']['id']],false);
                if ($result2['code']!=UserAccountManager::$successCode){
                    throw new Exception($result2['message']);
                }
                $resUpdate = ['pay_state'=>Order::PAY_STATE_SUCCESS,'pay_date'=>time(),'up_date'=>time()];
                $resultOrder = OrderManager::modify($result['data']['id'],$resUpdate,false);
                if ($resultOrder['code']!=OrderManager::$successCode){
                    throw new Exception($resultOrder['message']);
                }


                /**
                 * 如果当前支付人是发起人 ，修改组队信息
                 */
                if ($user->id == $relationInfo['captain']){

                    $resBasicUpdate = ['pay_state'=>Order::PAY_STATE_SUCCESS,'pay_date'=>time(),'up_date'=>time()];
                    $resultBasicOrder = OrderManager::modify($resultBasic['data']['id'],$resBasicUpdate,false);
                    if ($resultBasicOrder['code']!=OrderManager::$successCode){
                        throw new Exception($resultBasicOrder['message']);
                    }

                    $teamUpdate = ['pay_status'=>Team::PAY_STATUS_SUCCESS,'release'=>Team::RELEASE_STATUS_SUCCESS,'up_date'=>time()];
                    $teamResult = GroupManager::modify($relationInfo['t_id'],$teamUpdate,false);
                    if ($teamResult['code']!=GroupManager::$successCode){
                        throw new Exception('组队信息修改失败');
                    }
                }

                $upgradeResult = UserAccountManager::LevelUpgrade($user->id,'upgrade',false);
                if ($upgradeResult['code']!=UserAccountManager::$successCode){
                    throw new Exception($upgradeResult['message']);
                }

                if (!UserAccount::where(['user_id'=>$user->id])->update([
                    'join_count'=>Db::raw('join_count + 1'),
                    'team_count'=>Db::raw('team_count + 1'),
                    'version'=>Db::raw('version + 1')
                ])) {
                    throw new Exception('账户消费金额累加失败');
                }

                if ($assistantCount > 0){

                    if(!\app\common\model\assistant\Order::where('order_id',$result['data']['id'])->update(['pay_status'=>\app\common\model\assistant\Order::PAY_STATUS_YES,'update_time'=>time()])){
                        throw new Exception('助教订单状态修改失败');
                    }

                    if(!AssistantOrder::where('order_id',$result['data']['id'])->update(['pay_status'=>\app\common\model\assistant\Order::PAY_STATUS_YES,'update_time'=>time()])){
                        throw new Exception('用户助教订单状态修改失败');
                    }
                }

                $specialResult = GroupManager::specialModify($relationInfo['t_id'],false);
                if ($specialResult['code']!=GroupManager::$successCode){
                    throw new Exception($specialResult['message']);
                }

                $inviteCode = new InviteCode();
                $invite = $inviteCode->enCode();

                $teamJoiner = ['user_id'=>$user->id,'team'=>$relationInfo['t_id'],'state'=>UserTeam::STATE_SUCCESS,'pay_state'=>UserTeam::PAY_STATUS_SUCCESS,'order_id'=>$result['data']['id'],'sign_id'=>$signId,'verif_code'=>$invite,'ct_date'=>time(),'up_date'=>time()];
                $joinerResult = GroupManager::TeamJoinerInsert($relationInfo['t_id'],$teamJoiner,false);
                if ($joinerResult['code']!=GroupManager::$successCode){
                    throw new Exception('组队人员信息创建失败，订单取消');
                }
                $is_success = 1;
                if ($isTrans)
                    Db::commit();
                $prePayment = null;

            }else{
                if (!$prePayment){
                    $result1 = PayLogManager::record(['user_id'=>$user->id,'method'=>self::METHOD,'type'=> $type=='alipay' ? self::TYPE_ALIPAY : self::TYPE_WECHAT,'order'=>$order,'money'=>$real_money,'create_time'=>time()]);
                    $returnUrl = \config('app.returnUrl');
                    if ($type=='wechat'){
                        $notifyUrl = \config('app.notifyWechatUrl');
                    }else if ($type=='alipay'){
                        $notifyUrl = \config('app.notifyAlipayUrl');
                    }
                    if ($result['code'] == OrderManager::$successCode && $result1['code'] == PayLogManager::$successCode) {
                        if ($isTrans)
                            Db::commit();

                        //file_put_contents('a.txt',$notifyUrl,FILE_APPEND);
                        $prePayment = Service::submitOrder($real_money,$order,$type,\app\common\model\Order::TYPE_ARRAY[\app\common\model\Order::TYPE_TEAM]['name'],$notifyUrl,$returnUrl,$method,$user->open_id,$time_expire,['relation_id'=>$relationId]);
                        $resUpdate = ['pre_payment'=>$prePayment,'up_date'=>time()];
                        $resultOrder = OrderManager::modify($result['data']['id'],$resUpdate,false);
                        if ($resultOrder['code']!=OrderManager::$successCode){
                            throw new Exception('订单信息修改失败');
                        }
                        if($result1['data']['id']){
                            $id = $result1['data']['id'];
                            $update = ['request'=>serialize($prePayment)];
                            PayLogManager::modify($id,$update);
                        }
                    }else{
                        throw new Exception($result['message'].'或'.$result1['message']);
                    }
                }

            }

            return ['code'=>1,'message'=>'success','data'=>['order'=>$result['data'],'is_success'=>$is_success??0,'pre_payment'=>$prePayment]];
        }catch (Exception $exception){
            if ($isTrans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage(),'data'=>null];
        }
    }
}